package br.ykhan.t5.ytools.menu.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.ioc.internal.util.Defense;

import br.ykhan.t5.ytools.menu.beans.SiteMenu;

/**
 * Utilities for the Menu Module
 * 
 * @author Everton Agner Ramos
 * @see CollectionUtils
 */
public abstract class Utils
{
	public static int occurrencesOf(String source, String str2Check)
	{
		Defense.notNull(source, "source");
		
		return StringUtils.countMatches(source, str2Check);
	}
	
	public static String getMenuPath(String fullPagePath)
	{
		Defense.notNull(fullPagePath, "fullPagePath");
		
		int levels = occurrencesOf(fullPagePath, Constants.URI_LEVELS_SEPARATOR);
		
		return levels == 0 ? "" : fullPagePath.substring(0, StringUtils.lastIndexOf(fullPagePath, Constants.URI_LEVELS_SEPARATOR));
	}

	public static boolean isEmptyMenu(SiteMenu menu)
	{
		Defense.notNull(menu, "menu");
		
		return CollectionUtils.isEmpty(menu.getSubMenus()) &&
			   CollectionUtils.isEmpty(menu.getPages());
	}

	public static void sortPageNamesByLevel(List<String> pageNames)
	{
		Defense.notNull(pageNames, "pageNames");
		
		int maiorNivel = 0;
		Map<Integer, List<String>> relacaoPaginas = new LinkedHashMap<Integer, List<String>>();
		
		for(String pageName : pageNames)
		{
			int nivel = occurrencesOf(pageName, Constants.URI_LEVELS_SEPARATOR);
			
			if(nivel > maiorNivel) maiorNivel = nivel;
			
			List<String> relacaoPaginasNivel = relacaoPaginas.get(nivel);
			
			if(relacaoPaginasNivel == null) relacaoPaginasNivel = new ArrayList<String>();
			
			relacaoPaginasNivel.add(pageName);
			
			relacaoPaginas.put(nivel, relacaoPaginasNivel);
		}
		
		pageNames.clear();
		
		for (int i = 0; i <= maiorNivel; i++)
			if(relacaoPaginas.containsKey(i))
			{
				Collections.sort(relacaoPaginas.get(i));
				pageNames.addAll(relacaoPaginas.get(i));
			}
	}
}
